#导包
from django.http import HttpResponse,   HttpResponseRedirect

#导入自定义数据库模型
from mysite.models import User
#到内置模板方法
from django.shortcuts import render

#定义视图方法
def get_ip(request):
    #打印头部信息
    # print(request.META)
    #获取ip信息
    if 'HTTP_X_FORWARDED_FOR' in request.META:
        ip = request.META.get('HTTP_X_FORWARDED_FOR')
    else:
        ip = request.META.get('REMOTE_ADDR')
    # return HttpResponse("打印头部网址")
    print("来访者的ip是" + str(ip))
    return HttpResponse("您的ip是" +str(ip))

#定义首页视图方法
def index(request):
    #入库操作
    #建立实例
    # user = User(username='root',password='root')
    #入库操作
    # user.save()

    #删除数据(删),delete()是方法
    # User.objects.filter(id=1).delete()

    #修改数据（改）
    # user = User.objects.get(id=2)
    #修改字段
    # user.username = "9107"
    #保存修改
    # user.save() 

    #修改数据方法二
    # User.objects.filter(id=4).update(password='1227432612')

    #查询全部数据，翻译为 selesct * from user;
    res = User.objects.all()
    # print(res)

    #查询限定操作 翻译为select * from user where username = "9107" and 逻辑使用多个参数传递
    res = User.objects.filter(username="9107",password="root")
    # print(res)

    #只取一条 翻译 select * from user where id =1
    #库里面必须有所查的id
    res_one = User.objects.get(id=2)
    # print(res_one)

    #排除条件 翻译 select * from user where username != "9107"
    res = User.objects.exclude(username='9107')

    #定义字段显示 翻译为select * from user where name="9107"
    res_s = User.objects.filter(username="9107").values("password")

    #排序  翻译为select * from user order by id  asc 倒叙使用 reverse()
    res = User.objects.filter(username='9107').order_by("id").reverse()

    #去虫 翻译为select distinct(username) from user where username = "9107"
    res_dis =  User.objects.filter(username='9107').values("username").distinct()
    print(res_dis)

    #取数量  翻译为select count(*) from user
    res_count = User.objects.filter(username='9107').count()
    

    return render(request,'d4_index.html',locals())


